package slh.movie;


import slh.ConSql;
import slh.comment.comment;
import slh.comment.commentDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/movieDetail")
public class MovieDetailServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");
        // 获取电影ID参数
        String idParam = request.getParameter("id");
        if (idParam == null || idParam.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少电影ID参数");
            return;
        }

        try {
            int id = Integer.parseInt(idParam);

            // 从数据库获取电影详情
            Movie movie = MovieDao.getMovieById(id);
            if (movie == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到该电影");
                return;
            }

            // 获取电影评论
            List<comment> comments = commentDao.getCommentsByContent(id, "movie");

            // 计算平均评分
            double avgRating = comments.stream()
                    .mapToInt(comment::getRating)
                    .average()
                    .orElse(0.0);
                commentDao commentDao= new commentDao();

                int[] ratingCounts = commentDao.getRatingDistribution(id, "movie"); // 传入conn

                // ... 其他代码
            // 设置请求属性
            request.setAttribute("userId",userId);
            request.setAttribute("movie", movie);
            request.setAttribute("comments", comments);
            request.setAttribute("avgRating", avgRating);
            request.setAttribute("ratingCounts",ratingCounts);
            // 转发到详情页
            request.getRequestDispatcher("slh/movieDetail.jsp").forward(request, response);

        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的电影ID格式");
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库访问错误");
        }
    }
}